package com.focus.wecenter.service.impl;

import com.focus.wecenter.service.UserService;
import com.focus.wecenter.dao.UserDao;
import com.focus.wecenter.pojo.User;
import com.focus.wecenter.util.Encrypt;
import com.focus.wecenter.util.Message;
import com.focus.wecenter.util.PageBean;
import com.focus.wecenter.web.vo.SearchResult;
import com.focus.wecenter.web.vo.UserForm;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 用户业务实现
 *
 * @author Lv Jing
 * @date 2018年01月05日 13:05
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    private static String[] urls = new String[]{"http://wenda.wecenter.com/uploads/avatar/000/00/00/02_avatar_mid.jpg", "http://wenda.wecenter.com/uploads/avatar/000/00/00/49_avatar_mid.jpg",
            "http://wenda.wecenter.com/uploads/avatar/000/00/63/82_avatar_mid.jpg", "http://wenda.wecenter.com/uploads/avatar/000/00/51/67_avatar_mid.jpg",
    "http://wenda.wecenter.com/uploads/avatar/000/00/05/90_avatar_mid.jpg", "http://wenda.wecenter.com/uploads/avatar/000/00/14/20_avatar_mid.jpg",
    "http://wenda.wecenter.com/uploads/avatar/000/01/35/64_avatar_mid.jpg", "http://wenda.wecenter.com/uploads/avatar/000/00/00/35_avatar_mid.jpg",
            "http://wenda.wecenter.com/uploads/avatar/000/02/00/67_avatar_mid.jpg", "http://wenda.wecenter.com/uploads/avatar/000/01/71/87_avatar_mid.jpg"};

    @Override
    public boolean checkUsername(String username) {
        User user = userDao.findUserByUsername(username);
        return user!=null;
    }

    @Override
    public boolean checkEmail(String email) {
        return userDao.findUserByEmail(email) != null;
    }

    @Override
    public void register(UserForm user) {
        User entity = new User();

        // TODO:头像目前是随机固定的
        entity.setHeadPortrait(urls[new Random().nextInt(10)]);

        entity.setUsername(user.getUser_name());
        entity.setEmail(user.getEmail());
        entity.setJob(user.getJob());
        entity.setProvince(user.getProvince());
        entity.setCity(user.getCity());
        entity.setIntroduction(user.getSignature());
        entity.setCreateTime(new Date());
        entity.setSex(user.getSex());
        entity.setIntegral(100);

        // TODO: Md5Crypt.md5Crypt不知道怎么用了，貌似salt的格式有要求，换成shiro
        entity.setSalt(UUID.randomUUID().toString().replace("-", ""));
        entity.setPassword(Encrypt.md5(user.getPassword(), entity.getSalt()));

        userDao.add(entity);
    }

    @Override
    public User login(String username, String password) {
        boolean flag = false;
        User user = userDao.findUserByUsername(username);
        // 查看密码是否与md5加密一样
        if (user != null && Encrypt.md5(password, user.getSalt()).equals(user.getPassword())) {
            flag = true;
        }

        if (!flag) {
            user = userDao.findUserByEmail(username);
            if (user != null && Encrypt.md5(password, user.getSalt()).equals(user.getPassword())) {
                flag = true;
            }
        }

        if (flag) {
            return user;
        }
        return null;
    }

    @Override
    public User findByID(int userID) {
        return userDao.findById(userID);
    }

    @Override
    public PageBean<User> findByPage(int currentPage, int pageSize) {
        DetachedCriteria criteria = DetachedCriteria.forClass(User.class);
        criteria.addOrder(Order.desc("questionCount"));
        return userDao.findByPage(criteria, currentPage, pageSize);
    }

    @Override
    public User findByUsername(String username) {
        return userDao.findUserByUsername(username);
    }

    @Override
    public Message focusUser(int followID, int fansID) {
        Message message = new Message();
        // 查找用户
        User follow = userDao.findById(followID);
        if (follow == null) {
            message.setSuccess(false);
            message.setData("被关注人不存在");
            return message;
        }
        User fans = userDao.findById(fansID);
        if (fans == null) {
            message.setSuccess(false);
            message.setData("关注人不存在");
            return message;
        }
        // 判断粉丝是否关注了用户
        if (fans.getFocusUsers().contains(follow)) {
            // 关注了就取关
            fans.getFocusUsers().remove(follow);
            fans.setConcernCount(fans.getConcernCount() - 1);
            follow.setFansCount(follow.getFansCount() - 1);
            message.setSuccess(true);
            message.setData("remove");
            return message;
        }
        // 用户关注关联
        fans.getFocusUsers().add(follow);
        fans.setConcernCount(fans.getConcernCount() + 1);
        follow.setFansCount(follow.getFansCount() + 1);
        message.setSuccess(true);
        message.setData("add");
        return message;
    }

    @Override
    public List<SearchResult> searchUser(String query, int limit) {
        DetachedCriteria criteria = DetachedCriteria.forClass(User.class);
        criteria.add(Restrictions.like("username", query, MatchMode.ANYWHERE).ignoreCase());
        PageBean<User> pageResult = userDao.findByPage(criteria, 1, limit);
        List<SearchResult> results = new ArrayList<>();
        for (User user : pageResult.getList()) {
            SearchResult result = new SearchResult();
            result.setId(user.getId());
            result.put("url", "people/" + user.getUsername());
            result.setType("users");
            result.put("signature", user.getIntroduction());
            result.put("img", user.getHeadPortrait());
            result.put("name", user.getUsername());
            results.add(result);
        }
        return results;
    }
}
